// JavaScript Document
/*
panel
pagination
linkbutton
;zenghao
*/
(function($) {

    function getSelectedRoomData(target) {
        return $.data(target, 'selectedRoom');
    }

    function loadData(target, data) {
        var opts = $.data(target, 'floor').options;
        var colnum = opts.colnum; //每层有多少列
        var roomcell_html = opts.roomcell_html;
        //var selectedRoom = $.data(target, 'floor').selectedRoom;

        //$(target).empty();//清空
        var floordata = data; floordata != undefined ? floordata : {};
        var floors = floordata.rows != undefined ? floordata.rows : [];

        var floorhead_html = '';
        for (var i = 0; i < floors.length; i++) {
            floorhead_html += '<a href="#floors' + i + '" style="color:#99BBE8">' + floors[i]['floortext'] + '</a>&nbsp;'
        }

        var floor_html = '<table cellspacing="0" cellpadding="0" border="0" width="100%">';

        for (var i = 0; i < floors.length; i++) {
            //创建房间的html代码
            var room_html = '<table ><tbody>';
            var rooms = floors[i]['room'];
            var num = rooms.length > 0 ? (rooms.length % colnum > 0 ? 1 + (rooms.length - rooms.length % colnum) / colnum : rooms.length / colnum) : 0; //根据每层的列数得到一层要有多少行
            for (var k = 0; k < num; k++) {//循环创建行<tr>
                room_html += '<tr>';
                for (var j = k * colnum; j < (rooms.length > (k + 1) * colnum ? (k + 1) * colnum : rooms.length); j++) {//创建房间
                    room_html +=
				'<td style="padding:' + opts.roomspace + 'px;">' +
				'<div class="room-body" roomIndex="' + i + '-' + j + '">' + //指定每一个房间的序号				
					'<div class="room-head">' + rooms[j][opts.roomheadfield] + '</div>' +
					'<div class="room-cell">';
                    var HTML = $(roomcell_html).wrap("<div></div>").parent();
                    for (var m in rooms[j]) {//加载模板代码并解析成相应的值
                        HTML.find('a[name="' + m + '"]').append(rooms[j][m]);
                    }
                    room_html += HTML.html();
                    room_html += '</div>' +
				'</div>' +
			    '</td>';
                }
                room_html += '</tr>';
            }
            room_html += '</tbody></table>';
            //创建楼层头html代码
            var floor_head = '';
            if (floors.length > 1) {//如果只有一层就不显示头
                floor_head = '<div class="floor-header">&nbsp;&nbsp;<a name="floors' + i + '" style="font-weight:bold;font-size:15px">' + floors[i]['floortext'] + '</a>&nbsp;>&nbsp;' + floorhead_html + '</div>';
            } else {
                $('.floor-pager', target).pagination({ total: data.total });
            }
            //链接楼层、层头、房间的html代码
            floor_html +=
		   '<tr>' +
			'<td>' +
			'<div style="padding:2px; border:none;">' + floor_head + '<div>' +
			room_html +
			'</div></div>' +
			'</td>' +
		  '</tr>';

        }
        floor_html += '</table>';

        $(floor_html).appendTo($('.floor-view', target)); //把生产的html代码添加到父panel里
        //$(target).panel();

        $('.room-body', target).width(opts.roomsize.roomWidth);
        $('.room-body', target).height(opts.roomsize.roomHeight);

        $('.room-cell', target).height(opts.roomsize.roomHeight - $('.room-head', target).height()); //房间内容的高度等于房间的高度减去房间头的高度


        $('.room-body', target).mouseover(function() {
            $(this).addClass('floor-room-over');
        }).mouseout(function() {
            $(this).removeClass('floor-room-over');
        }).click(function() {
            var floorindex = $(this).attr('roomIndex').split('-')[0];
            var roomindex = $(this).attr('roomIndex').split('-')[1];
            var roomdata = data.rows[floorindex].room[roomindex]; //根据指定房间的序号从数据对象中取出房间对象
            $.data(target, 'selectedRoom', roomdata); //把房间对象缓存
            if ($(this).hasClass('floor-room-selected')) {
                //$(this).removeClass('floor-room-selected');
                if (opts.onUnselect) {//取消选择事件
                    opts.onUnselect.call(this, $(this).attr('roomIndex'), roomdata);
                }
            } else {
                $('.room-body', target).removeClass('floor-room-selected');
                $(this).addClass('floor-room-selected');

                if (opts.onSelect) {//选择事件
                    opts.onSelect.call(this, $(this).attr('roomIndex'), roomdata);
                }
            }

            if (opts.onClickRoom) {//单击事件
                opts.onClickRoom.call(this, $(this).attr('roomIndex'), roomdata);
            }
        }).dblclick(function() {
            var floorindex = $(this).attr('roomIndex').split('-')[0];
            var roomindex = $(this).attr('roomIndex').split('-')[1];
            var roomdata = data.rows[floorindex].room[roomindex];
            if (opts.onDblClickRoom) {//双击事件
                opts.onDblClickRoom.call(this, $(this).attr('roomIndex'), roomdata);
            }
        });

        $('.room-body', target).each(function() {
            var floorindex = $(this).attr('roomIndex').split('-')[0];
            var roomindex = $(this).attr('roomIndex').split('-')[1];
            var roomdata = data.rows[floorindex].room[roomindex];
            opts.roomFormatStyle.call(this, this, roomdata);
        });
    }

    function request(target) {
        var opts = $.data(target, 'floor').options;
        if (!opts.url) return;

        var param = $.extend({}, opts.queryParams);
        if (opts.pagination) {
            $.extend(param, {
                page: opts.pageNumber,
                rows: opts.pageSize
            });
        }

        $('.floor-pager', target).pagination({ loading: true });


        $('.floor-view table', target).remove(); //请求数据前先清除数据
        var wrap = $('.floor-view', target); //$.data(target, 'floor').panel;
        var mask = $('<div class="floor-mask"></div>').css({
            display: 'block',
            width: wrap.width(),
            height: wrap.height()//-$('.floor-toolbar',target).outerHeight()
        }).appendTo(wrap);
        $('<div class="floor-mask-msg"></div>')
				.html(opts.loadMsg)
				.appendTo(mask)
				.css({
				    display: 'block',
				    left: (wrap.width() - $('.floor-mask-msg', target).outerWidth()) / 2,
				    top: (wrap.height() - $('.floor-mask-msg', target).outerHeight()) / 2
				});

        $.ajax({
            type: 'POST',
            url: opts.url,
            data: param,
            dataType: 'json',
            success: function(data) {
                setTimeout(function() {
                    if (data) {
                        $.data(target, 'floor').data = data;
                        $('.floor-pager', target).pagination({ total: data.total });
                        loadData(target, data);

                        $.removeData(target, 'selectedRoom'); //
                    }

                    $('.floor-pager', target).pagination({ loading: false });
                    $('.floor-mask', target).remove();
                    $('.floor-mask-msg', target).remove();
                }, 0);

            },
            error: function() {
                setTimeout(function() {
                    //$.data(target, 'floor').data = data;
                    //loadData(target, data);

                    //$('.floor-pager', target).pagination({total: data.total});
                    $('.floor-pager', target).pagination({ loading: false });
                    $('.floor-mask', target).remove();
                    $('.floor-mask-msg', target).remove();
                }, 0);
            }
        });
    }

    $.fn.floor = function(options, param) {
        if (typeof options == 'string') {
            switch (options) {
                case 'options':
                    return $.data(this[0], 'floor').options;

                case 'getSelectedRoomData':
                    return getSelectedRoomData(this[0]);

                case 'reload':
                    return this.each(function() {
                        request(this);
                    });
                case 'getData':
                    return $.data(this[0], 'floor').data;
                case 'loadData':
                    return this.each(function() {
                        loadData(this, param);
                    });
                case 'getPager':
                    return $.data(this[0], 'floor').panel.find("div.floor-pager");
                case 'getPanel':
                    return $.data(this[0], 'floor').panel;
            }


        }

        options = options || {};
        return this.each(function() {
            var state = $.data(this, 'floor');
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
                state.options = opts;
            } else {
                opts = $.extend({}, $.fn.floor.defaults, options);

                $.data(this, 'floor', {
                    options: opts//,
                    //floorbody:$(this),
                    //selectedRoom: {}
                });
            }
            var target = this;
            //$.data(this, 'floor').panel=$(target).panel();



            if (opts.toolbar) {
                if (typeof opts.toolbar == "string") {
                    $(opts.toolbar).addClass("floor-toolbar").appendTo($(target));
                    $(opts.toolbar).show();
                } else {
                    $('.floor-toolbar', target).remove();
                    var tb = $('<div class="floor-toolbar"></div>').appendTo($(target));
                    for (var i = 0; i < opts.toolbar.length; i++) {
                        var btn = opts.toolbar[i];
                        if (btn == '-') {
                            $('<div class="floor-btn-separator"></div>').appendTo(tb);
                        } else {
                            var tool = $('<a href="javascript:void(0)"></a>');
                            tool[0].onclick = eval(btn.handler || function() { });
                            tool.css('float', 'left')
								.text(btn.text)
								.attr('icon', btn.iconCls || '')
								.appendTo(tb)
								.linkbutton({
								    plain: true,
								    disabled: (btn.disabled || false)
								});
                        }
                    }
                }
            }

            $('.floor-view', target).remove();
            $('<div class="floor-view"></div>').appendTo($(target));

            $('.floor-pager', target).remove();
            if (opts.pagination) {
                var pager = $('<div class="floor-pager"></div>').appendTo($(target));
                pager.pagination({
                    pageNumber: opts.pageNumber,
                    pageSize: opts.pageSize,
                    pageList: opts.pageList,
                    onSelectPage: function(pageNum, pageSize) {
                        // save the page state
                        opts.pageNumber = pageNum;
                        opts.pageSize = pageSize;
                        if (opts.url) {
                            request(target); // request new page data
                        }
                    }
                });
                opts.pageSize = pager.pagination('options').pageSize; // repare the pageSize value
            }

            //$('.floor-view', target).width($(target).width());
            //$('.floor-view', target).height($(target).height()-$('.floor-toolbar',target).outerHeight()-$('.floor-pager',target).outerHeight());
            //存入缓存，给查找分页控件方法使用
            $.data(this, 'floor').panel = $(target).panel({
                onResize: function(width, height) {
                    $('.floor-view', target).width($(target).width());
                    $('.floor-view', target).height($(target).height() - $('.floor-toolbar', target).outerHeight() - $('.floor-pager', target).outerHeight());
                }
            });

            if (opts.url) {
                request(target);
            }

            //var data=$.data(target, 'floor').data;


        });
    };

    $.fn.floor.defaults = {
        url: null,
        loadMsg: '加载中, 请等待 ...',
        roomsize: { roomWidth: 100, roomHeight: 100 },
        colnum: 10, //每层最多有多少列
        //panelparam:{},
        roomspace: 1,
        roomheadfield: 'roomnumber',
        roomcell_html: '',

        pagination: false,
        pageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 30, 40, 50],
        queryParams: {},
        roomFormatStyle: function(roomTarget, roomdata) { },
        onClickRoom: function(roomIndex, roomdata) { },
        onDblClickRoom: function(roomIndex, roomdata) { },
        onSelect: function(roomIndex, roomdata) { },
        onUnselect: function(roomIndex, roomdata) { }
    };
})(jQuery);